package com.lemon.security.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 李猛
 * @datetime 2024/2/6 23:28
 * @description 登录用户的身份权限信息
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class LoginUserDetail implements UserDetails {
    /**
     * 扩展字段
     */
    private Long userId;//用户ID
    private Long tenantId;//租户ID
    private String name;//姓名
    private List<String> resourceList;//资源列表

    /**
     * 默认字段
     */
    private String username;//登录名
    private String password;
    private Boolean enabled;
    private Collection<GrantedAuthority> authorities;

    public Collection<GrantedAuthority> getAuthorities() {
        if (!CollectionUtils.isEmpty(authorities)) {
            return authorities;
        }
        if (!CollectionUtils.isEmpty(resourceList)) {
            //把资源中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
            return resourceList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
